package com.yu.springboot_project_yu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Arrays;
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    // 配置安全过滤器链
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 禁用CSRF保护
        http
            .csrf(csrf -> csrf.disable())
            // 配置跨域资源共享
            .cors(cors -> cors.configurationSource(corsConfigurationSource()))
            // 配置授权请求
            .authorizeHttpRequests(auth -> auth
                // 允许所有请求
                .requestMatchers("/**").permitAll()
            );
        // 构建安全过滤器链
        return http.build();
    }

    // 配置跨域资源共享
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        // 创建跨域配置
        CorsConfiguration configuration = new CorsConfiguration();
        // 允许的源
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:8088"));
        // 允许的方法
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        // 允许的头部
        configuration.setAllowedHeaders(Arrays.asList("*"));
        // 是否允许发送Cookie
        configuration.setAllowCredentials(true);
        
        // 创建URL基础跨域配置源
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 注册跨域配置
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}